/**
 * The DITA example app (and xsl/prepareXIncludes.xsl) uses its own
 * uri protocol so that there's a nice xml:base to work with. 
 *
 * Your implementation probably needs different access methods to a file
 * repository. 
 */
function loadXML(uri)
{
  var realURI = '' + uri;
  if (uri.match(/^urn:xopus-dita-example:/)) {
    realURI = uri.replace(/^urn:xopus-dita-example:(.*)(#.+)?$/, '$1');
  }
  return HTTPTools.getXML(realURI);
}


function saveXML(uri, xmlDocument)
{
  var realURI = '';
  if (uri.match(/^urn:xopus-dita-example/)) {
    realURI = uri.replace(/^urn:xopus-dita-example:(.*)(#.+)?$/, '?id=$1');
  } else {
    // Clean out content of conref having elements
    realURI = uri.substring(uri.indexOf("?fileId="));
  }
  var result = HTTPTools.postXML("save-xml.php" + realURI + "&save=true", xmlDocument, "UTF-8");

  if (xmlDocument.documentElement.tagName)
    top.document.getElementById('navigation').contentWindow.location.reload();

  if (result != "Ok")
  {
    alert(result);
    return false;
  }
  else
    return true;
}


function exit()
{
  if (confirm("Are you sure you want to close this document?")) {
    document.location.href =
      document.location.href.replace(
          /\/view-xopus-island_remote\.php.*$/,
          "/view-xopus-island-empty.php");
  }
}


/* Event handling ======================================================= */
/**
 * Add extra markup to elements that can't be handled with templates (see
 * loca.xml). 
 */
function afterChildInserted(evt)
{
  var node = evt.childNode;

  if (1 == node.getNodeType()) 
  {
    /*
    var className = node.getAttribute("class") || "";
    if (-1 != className.search(/\s(topic\/topic)\s/))
    {
      node.setAttribute("id", "id" + (new UUID()).toString());
    }
    */
    //
    // Turn on rendering, so that you can actually type in this element. UI
    // reminder: with lots of of these elements in a doc, turning on this
    // setting gives a blinking re-rendering effect and the author needs to
    // look carefully where the cursor is placed. 
    if (node.getLocalName() == "draft-comment") 
    {
      Editor.getScope().set("show-draft-comment", true);
    }
    else if (node.getLocalName() == "required-cleanup") 
    {
      Editor.getScope().set("show-required-cleanup", true);
    }
  }
}


/**
 * Schema helper: Check if we need to fill in a reference value.
 *
 * This list of owner elements should match the list of lookups on href
 * attributes in local.xml.
 */
function afterAttributeInserted(evt)
{
  if (evt.attrNode.getLocalName() == "href")
  {
    var className = evt.attrNode.getOwnerElement().getAttribute("class") || "";
    if (   -1 != className.search(/\s(topic\/image)\s/)
        || -1 != className.search(/\s(map\/topicref)\s/))
    {
      evt.attrNode.showLookup();
    }
  }
}

/**
 * Schema helper: prevent editing of class attributes
 */
function beforeNodeValueModified(evt)
{
  if(evt.target.getLocalName() == "class")
    evt.preventDefault();
}


/**
 * Add a new element of the given type to this refnode.
 *
 * @see xsl/map.xsl
 */
function addNode(refnode, type)
{
  var doc = refnode.getOwnerDocument();
  var newnode = doc.createElement(type);
  var parent = refnode.getParentNode();

  if (refnode.getNextSibling() != null)
    parent.insertBefore(newnode, refnode.getNextSibling());
  else
    parent.appendChild(newnode);

  newnode.makeComplete();
  if (type == "topicref")
  {
    newnode.setAttribute("href","");
    newnode.getAttributeNode("href").showLookup();
  }
}


function onLoadDocument(evt)
{
  var doc = evt.document;
  doc.addEventListener("XopusAfterChildInserted", afterChildInserted);
  doc.addEventListener("XopusAfterAttrInserted", afterAttributeInserted);
  doc.addEventListener("XopusBeforeNodeValueModified", beforeNodeValueModified);
}


function onUnloadDocument(evt)
{
  var doc = evt.document;
  doc.removeEventListener("XopusAfterChildInserted", afterChildInserted);
  doc.removeEventListener("XopusAfterAttrInserted", afterAttributeInserted);
  doc.removeEventListener("XopusBeforeNodeValueModified", beforeNodeValueModified);
}


function showDraftComments(show)
{
  var canvas = Editor.Canvas.getActiveCanvas();
  if (!canvas) return;
  canvas.setViewParam("show-draft-comments", show);
}


function showRequiredCleanup(show)
{
  var canvas = Editor.Canvas.getActiveCanvas();
  if (!canvas) return;
  canvas.setViewParam("show-required-cleanups", show);
}


/* Connect to the Xopus API =============================================== */
IO.loadCatalog("xopus/dita/xsd/catalog.xml");
IO.setLoadXMLFunction(loadXML);
IO.setSaveXMLFunction(saveXML);
Editor.addEventListener("load", onLoadDocument);
Editor.addEventListener("unload", onUnloadDocument);
Editor.setExitFunction(exit);
// See dita.commands.* which depend on these variables:
Editor.getScope().declare("show-draft-comment", false);
Editor.getScope().setListener("show-draft-comment", showDraftComments);
Editor.getScope().declare("show-required-cleanup", false);
Editor.getScope().setListener("show-required-cleanup", showRequiredCleanup);
Editor.addCommand("showDraftCommentsCommand", dita.commands.ShowDraftCommentsCommand);
Editor.addCommand("showRequiredCleanupCommand", dita.commands.ShowRequiredCleanupCommand);
